// 游戏主逻辑
class SnakeGame {
    constructor() {
        // 获取画布和绘图上下文
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        
        // 设置画布尺寸
        this.canvas.width = 600;
        this.canvas.height = 400;
        
        // 游戏配置
        this.gridSize = 20;
        this.fps = 10;
        this.speed = 1000 / this.fps;
        
        // 游戏状态
        this.gameRunning = false;
        this.gamePaused = false;
        this.score = 0;
        this.level = 1;
        this.highScore = localStorage.getItem('snakeHighScore') || 0;
        
        // 音效控制
        this.soundEnabled = true;
        this.sounds = {
            eat: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-arcade-game-jump-coin-216.mp3'),
            gameOver: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-player-losing-or-failing-2042.mp3'),
            powerUp: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-unlock-game-notification-253.mp3')
        };
        
        // 蛇的初始状态
        this.resetGame();
        
        // 绑定事件处理
        this.bindEvents();
        
        // 渲染初始画面
        this.render();
    }
    
    // 重置游戏状态
    resetGame() {
        // 蛇的初始位置和方向
        this.snake = [
            {x: 5, y: 5},
            {x: 4, y: 5},
            {x: 3, y: 5}
        ];
        this.direction = 'right';
        this.nextDirection = 'right';
        
        // 重置游戏数据
        this.score = 0;
        this.level = 1;
        this.fps = 10;
        this.speed = 1000 / this.fps;
        this.gameRunning = false;
        this.gamePaused = false;
        
        // 生成食物
        this.generateFood();
        this.generateSpecialFood();
        
        // 更新UI
        this.updateScore();
        document.getElementById('gameStatus').textContent = '按空格键或点击开始按钮开始游戏！';
    }
    
    // 绑定事件监听器
    bindEvents() {
        // 键盘控制
        document.addEventListener('keydown', (e) => {
            // 游戏控制键
            if (e.code === 'Space') {
                if (!this.gameRunning) {
                    this.startGame();
                } else {
                    this.togglePause();
                }
                return;
            }
            
            // 方向控制
            if (this.gameRunning && !this.gamePaused) {
                switch(e.code) {
                    case 'ArrowUp':
                    case 'KeyW':
                        if (this.direction !== 'down') this.nextDirection = 'up';
                        break;
                    case 'ArrowDown':
                    case 'KeyS':
                        if (this.direction !== 'up') this.nextDirection = 'down';
                        break;
                    case 'ArrowLeft':
                    case 'KeyA':
                        if (this.direction !== 'right') this.nextDirection = 'left';
                        break;
                    case 'ArrowRight':
                    case 'KeyD':
                        if (this.direction !== 'left') this.nextDirection = 'right';
                        break;
                }
            }
        });
        
        // 按钮控制
        document.getElementById('start-btn').addEventListener('click', () => {
            if (!this.gameRunning) {
                this.startGame();
            }
        });
        
        document.getElementById('pause-btn').addEventListener('click', this.togglePause.bind(this));
        document.getElementById('reset-btn').addEventListener('click', this.resetGame.bind(this));
        document.getElementById('sound-btn').addEventListener('click', this.toggleSound.bind(this));
        
        // 移动设备控制按钮
        document.getElementById('up-btn').addEventListener('click', () => {
            if (this.gameRunning && !this.gamePaused && this.direction !== 'down') {
                this.nextDirection = 'up';
            }
        });
        
        document.getElementById('down-btn').addEventListener('click', () => {
            if (this.gameRunning && !this.gamePaused && this.direction !== 'up') {
                this.nextDirection = 'down';
            }
        });
        
        document.getElementById('left-btn').addEventListener('click', () => {
            if (this.gameRunning && !this.gamePaused && this.direction !== 'right') {
                this.nextDirection = 'left';
            }
        });
        
        document.getElementById('right-btn').addEventListener('click', () => {
            if (this.gameRunning && !this.gamePaused && this.direction !== 'left') {
                this.nextDirection = 'right';
            }
        });
        
        // 窗口大小调整
        window.addEventListener('resize', this.handleResize.bind(this));
    }
    
    // 处理窗口大小调整
    handleResize() {
        // 这里可以添加响应式调整逻辑
    }
    
    // 开始游戏
    startGame() {
        if (this.gameRunning) return;
        
        this.gameRunning = true;
        this.gamePaused = false;
        document.getElementById('gameStatus').textContent = '游戏进行中！';
        this.gameLoop();
    }
    
    // 暂停/继续游戏
    togglePause() {
        if (!this.gameRunning) return;
        
        this.gamePaused = !this.gamePaused;
        
        if (this.gamePaused) {
            document.getElementById('gameStatus').textContent = '游戏已暂停！';
            if (this.gameLoopId) {
                clearTimeout(this.gameLoopId);
                this.gameLoopId = null;
            }
        } else {
            document.getElementById('gameStatus').textContent = '游戏继续！';
            this.gameLoop();
        }
    }
    
    // 切换音效开关
    toggleSound() {
        this.soundEnabled = !this.soundEnabled;
        const soundBtn = document.getElementById('sound-btn');
        soundBtn.textContent = this.soundEnabled ? '🔊 音效' : '🔇 静音';
    }
    
    // 播放音效
    playSound(soundName) {
        if (this.soundEnabled && this.sounds[soundName]) {
            try {
                // 重置音效并播放
                this.sounds[soundName].currentTime = 0;
                this.sounds[soundName].play().catch(e => console.log('播放音效失败:', e));
            } catch (e) {
                console.log('播放音效时出错:', e);
            }
        }
    }
    
    // 生成普通食物
    generateFood() {
        let newFood;
        do {
            newFood = {
                x: Math.floor(Math.random() * (this.canvas.width / this.gridSize)),
                y: Math.floor(Math.random() * (this.canvas.height / this.gridSize))
            };
        } while (this.checkCollision(newFood, this.snake));
        
        this.food = newFood;
        this.foodType = 'normal';
        this.foodValue = 10;
    }
    
    // 生成特殊食物
    generateSpecialFood() {
        // 10%的概率生成特殊食物
        if (Math.random() < 0.1) {
            let newFood;
            do {
                newFood = {
                    x: Math.floor(Math.random() * (this.canvas.width / this.gridSize)),
                    y: Math.floor(Math.random() * (this.canvas.height / this.gridSize))
                };
            } while (this.checkCollision(newFood, this.snake) || 
                     (this.food && newFood.x === this.food.x && newFood.y === this.food.y));
            
            // 随机选择特殊食物类型
            const specialTypes = ['bonus', 'speedUp', 'slowDown', 'extraLife', 'lengthBonus'];
            this.specialFood = newFood;
            this.specialFoodType = specialTypes[Math.floor(Math.random() * specialTypes.length)];
            this.specialFoodTimer = 15000; // 特殊食物存在15秒
            
            // 特殊食物出现的视觉提示
            this.showSpecialFoodIndicator();
        } else {
            this.specialFood = null;
            this.specialFoodType = null;
        }
    }
    
    // 显示特殊食物出现的提示
    showSpecialFoodIndicator() {
        const statusEl = document.getElementById('gameStatus');
        const originalText = statusEl.textContent;
        let indicatorText = '';
        
        switch(this.specialFoodType) {
            case 'bonus':
                indicatorText = '💎 高分食物出现！';
                break;
            case 'speedUp':
                indicatorText = '⚡ 加速食物出现！';
                break;
            case 'slowDown':
                indicatorText = '🐌 减速食物出现！';
                break;
            case 'extraLife':
                indicatorText = '❤️ 生命食物出现！';
                break;
            case 'lengthBonus':
                indicatorText = '📏 增长食物出现！';
                break;
        }
        
        statusEl.textContent = indicatorText;
        
        // 3秒后恢复原状
        setTimeout(() => {
            if (this.gameRunning && !this.gamePaused) {
                statusEl.textContent = originalText;
            }
        }, 3000);
    }
    
    // 检查碰撞
    checkCollision(head, array) {
        for (let i = 0; i < array.length; i++) {
            if (head.x === array[i].x && head.y === array[i].y) {
                return true;
            }
        }
        return false;
    }
    
    // 移动蛇
    moveSnake() {
        // 更新方向
        this.direction = this.nextDirection;
        
        // 获取蛇头位置
        const head = { ...this.snake[0] };
        
        // 根据方向移动蛇头
        switch(this.direction) {
            case 'up':
                head.y--;
                break;
            case 'down':
                head.y++;
                break;
            case 'left':
                head.x--;
                break;
            case 'right':
                head.x++;
                break;
        }
        
        // 检查是否撞到边界
        if (head.x < 0 || head.x >= this.canvas.width / this.gridSize || 
            head.y < 0 || head.y >= this.canvas.height / this.gridSize) {
            this.gameOver();
            return;
        }
        
        // 检查是否撞到自己
        if (this.checkCollision(head, this.snake)) {
            this.gameOver();
            return;
        }
        
        // 将新头部添加到蛇身体
        this.snake.unshift(head);
        
        // 检查是否吃到普通食物
        if (head.x === this.food.x && head.y === this.food.y) {
            // 增加分数
            this.score += this.foodValue;
            this.updateScore();
            
            // 播放吃食物音效
            this.playSound('eat');
            
            // 生成新食物
            this.generateFood();
            this.generateSpecialFood();
            
            // 每获得100分升级一次
            if (this.score % 100 === 0) {
                this.levelUp();
            }
        }
        // 检查是否吃到特殊食物
        else if (this.specialFood && head.x === this.specialFood.x && head.y === this.specialFood.y) {
            // 根据特殊食物类型执行不同效果
            this.applySpecialFoodEffect();
            
            // 播放特殊食物音效
            this.playSound('powerUp');
            
            // 清除特殊食物
            this.specialFood = null;
            this.specialFoodType = null;
        }
        // 如果没有吃到食物，移除尾部
        else {
            this.snake.pop();
        }
        
        // 更新特殊食物计时器
        if (this.specialFood) {
            this.specialFoodTimer -= this.speed;
            if (this.specialFoodTimer <= 0) {
                this.specialFood = null;
                this.specialFoodType = null;
            }
        }
    }
    
    // 应用特殊食物效果
    applySpecialFoodEffect() {
        switch(this.specialFoodType) {
            case 'bonus':
                // 高分食物
                const bonusPoints = Math.floor(Math.random() * 50) + 50; // 50-100分
                this.score += bonusPoints;
                document.getElementById('gameStatus').textContent = `获得${bonusPoints}额外分数！`;
                break;
            case 'speedUp':
                // 加速食物
                this.fps = Math.min(20, this.fps + 2);
                this.speed = 1000 / this.fps;
                document.getElementById('gameStatus').textContent = '速度提升！';
                break;
            case 'slowDown':
                // 减速食物
                this.fps = Math.max(5, this.fps - 2);
                this.speed = 1000 / this.fps;
                document.getElementById('gameStatus').textContent = '速度降低！';
                break;
            case 'extraLife':
                // 生命食物
                document.getElementById('gameStatus').textContent = '获得额外生命！';
                break;
            case 'lengthBonus':
                // 增长食物
                for (let i = 0; i < 3; i++) {
                    const tail = { ...this.snake[this.snake.length - 1] };
                    this.snake.push(tail);
                }
                document.getElementById('gameStatus').textContent = '蛇身增长！';
                break;
        }
        
        // 更新分数
        this.updateScore();
        
        // 3秒后恢复状态消息
        setTimeout(() => {
            if (this.gameRunning && !this.gamePaused) {
                document.getElementById('gameStatus').textContent = '游戏进行中！';
            }
        }, 3000);
    }
    
    // 升级
    levelUp() {
        this.level++;
        this.fps = Math.min(20, 10 + Math.floor(this.level / 2));
        this.speed = 1000 / this.fps;
        
        document.getElementById('level').textContent = this.level;
        document.getElementById('gameStatus').textContent = `恭喜升级到${this.level}级！速度提升！`;
        
        // 3秒后恢复状态消息
        setTimeout(() => {
            if (this.gameRunning && !this.gamePaused) {
                document.getElementById('gameStatus').textContent = '游戏进行中！';
            }
        }, 3000);
    }
    
    // 游戏结束
    gameOver() {
        this.gameRunning = false;
        this.playSound('gameOver');
        
        // 更新最高分
        if (this.score > this.highScore) {
            this.highScore = this.score;
            localStorage.setItem('snakeHighScore', this.highScore);
            document.getElementById('gameStatus').textContent = `游戏结束！新纪录：${this.score}分！按空格键重新开始。`;
        } else {
            document.getElementById('gameStatus').textContent = `游戏结束！得分：${this.score}分！按空格键重新开始。`;
        }
    }
    
    // 更新分数显示
    updateScore() {
        document.getElementById('score').textContent = this.score;
        document.getElementById('length').textContent = this.snake.length;
    }
    
    // 渲染游戏画面
    render() {
        // 清空画布
        this.ctx.fillStyle = '#0a0a0a';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制网格背景
        this.drawGrid();
        
        // 绘制蛇
        this.drawSnake();
        
        // 绘制食物
        this.drawFood();
        
        // 绘制特殊食物
        this.drawSpecialFood();
        
        // 如果游戏暂停，显示暂停提示
        if (this.gamePaused) {
            this.drawPauseIndicator();
        }
    }
    
    // 绘制网格背景
    drawGrid() {
        this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
        this.ctx.lineWidth = 0.5;
        
        // 绘制垂直线
        for (let x = 0; x <= this.canvas.width; x += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.canvas.height);
            this.ctx.stroke();
        }
        
        // 绘制水平线
        for (let y = 0; y <= this.canvas.height; y += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.canvas.width, y);
            this.ctx.stroke();
        }
    }
    
    // 绘制蛇
    drawSnake() {
        // 绘制蛇头
        const head = this.snake[0];
        this.ctx.fillStyle = '#00ff00';
        this.ctx.beginPath();
        this.ctx.roundRect(head.x * this.gridSize, head.y * this.gridSize, this.gridSize, this.gridSize, 5);
        this.ctx.fill();
        
        // 绘制蛇眼睛
        this.ctx.fillStyle = 'white';
        let eyeXOffset, eyeYOffset;
        
        switch(this.direction) {
            case 'up':
                eyeXOffset = [this.gridSize * 0.3, this.gridSize * 0.7];
                eyeYOffset = this.gridSize * 0.3;
                break;
            case 'down':
                eyeXOffset = [this.gridSize * 0.3, this.gridSize * 0.7];
                eyeYOffset = this.gridSize * 0.7;
                break;
            case 'left':
                eyeXOffset = [this.gridSize * 0.3, this.gridSize * 0.3];
                eyeYOffset = [this.gridSize * 0.3, this.gridSize * 0.7];
                break;
            case 'right':
                eyeXOffset = [this.gridSize * 0.7, this.gridSize * 0.7];
                eyeYOffset = [this.gridSize * 0.3, this.gridSize * 0.7];
                break;
        }
        
        if (Array.isArray(eyeXOffset)) {
            // 左右方向的眼睛
            if (Array.isArray(eyeYOffset)) {
                for (let i = 0; i < 2; i++) {
                    this.ctx.beginPath();
                    this.ctx.arc(
                        head.x * this.gridSize + eyeXOffset[i], 
                        head.y * this.gridSize + eyeYOffset[i], 
                        this.gridSize * 0.1, 
                        0, 
                        Math.PI * 2
                    );
                    this.ctx.fill();
                }
            }
            // 上下方向的眼睛
            else {
                for (let i = 0; i < 2; i++) {
                    this.ctx.beginPath();
                    this.ctx.arc(
                        head.x * this.gridSize + eyeXOffset[i], 
                        head.y * this.gridSize + eyeYOffset, 
                        this.gridSize * 0.1, 
                        0, 
                        Math.PI * 2
                    );
                    this.ctx.fill();
                }
            }
        }
        
        // 绘制蛇身体
        for (let i = 1; i < this.snake.length; i++) {
            const segment = this.snake[i];
            
            // 渐变颜色，越后面的身体颜色越深
            const alpha = Math.max(0.3, 1 - i * 0.03);
            this.ctx.fillStyle = `rgba(0, 255, 0, ${alpha})`;
            
            this.ctx.beginPath();
            this.ctx.roundRect(segment.x * this.gridSize, segment.y * this.gridSize, this.gridSize, this.gridSize, 3);
            this.ctx.fill();
        }
    }
    
    // 绘制普通食物
    drawFood() {
        if (!this.food) return;
        
        // 闪烁效果
        const currentTime = Date.now();
        const blinkRate = 500; // 闪烁频率
        const opacity = 0.7 + 0.3 * Math.sin(currentTime / blinkRate * Math.PI);
        
        this.ctx.fillStyle = `rgba(255, 0, 0, ${opacity})`;
        this.ctx.beginPath();
        this.ctx.arc(
            this.food.x * this.gridSize + this.gridSize / 2, 
            this.food.y * this.gridSize + this.gridSize / 2, 
            this.gridSize / 2, 
            0, 
            Math.PI * 2
        );
        this.ctx.fill();
    }
    
    // 绘制特殊食物
    drawSpecialFood() {
        if (!this.specialFood) return;
        
        // 根据特殊食物类型设置不同的颜色和形状
        switch(this.specialFoodType) {
            case 'bonus':
                // 钻石形状（简化为六边形）
                this.ctx.fillStyle = '#00ffff';
                this.ctx.beginPath();
                const centerX = this.specialFood.x * this.gridSize + this.gridSize / 2;
                const centerY = this.specialFood.y * this.gridSize + this.gridSize / 2;
                const radius = this.gridSize / 2.5;
                
                for (let i = 0; i < 6; i++) {
                    const angle = (Math.PI / 3) * i;
                    const x = centerX + radius * Math.cos(angle);
                    const y = centerY + radius * Math.sin(angle);
                    
                    if (i === 0) {
                        this.ctx.moveTo(x, y);
                    } else {
                        this.ctx.lineTo(x, y);
                    }
                }
                this.ctx.closePath();
                this.ctx.fill();
                break;
            case 'speedUp':
                // 闪电形状（简化为黄色圆形）
                this.ctx.fillStyle = '#ffff00';
                this.ctx.beginPath();
                this.ctx.arc(
                    this.specialFood.x * this.gridSize + this.gridSize / 2, 
                    this.specialFood.y * this.gridSize + this.gridSize / 2, 
                    this.gridSize / 2.5, 
                    0, 
                    Math.PI * 2
                );
                this.ctx.fill();
                break;
            case 'slowDown':
                // 蜗牛形状（简化为蓝色圆形）
                this.ctx.fillStyle = '#0000ff';
                this.ctx.beginPath();
                this.ctx.arc(
                    this.specialFood.x * this.gridSize + this.gridSize / 2, 
                    this.specialFood.y * this.gridSize + this.gridSize / 2, 
                    this.gridSize / 2.5, 
                    0, 
                    Math.PI * 2
                );
                this.ctx.fill();
                break;
            case 'extraLife':
                // 心形（简化为红色圆形）
                this.ctx.fillStyle = '#ff00ff';
                this.ctx.beginPath();
                this.ctx.arc(
                    this.specialFood.x * this.gridSize + this.gridSize / 2, 
                    this.specialFood.y * this.gridSize + this.gridSize / 2, 
                    this.gridSize / 2.5, 
                    0, 
                    Math.PI * 2
                );
                this.ctx.fill();
                break;
            case 'lengthBonus':
                // 长度形状（简化为绿色矩形）
                this.ctx.fillStyle = '#00ff00';
                this.ctx.fillRect(
                    this.specialFood.x * this.gridSize + this.gridSize * 0.15, 
                    this.specialFood.y * this.gridSize + this.gridSize * 0.15, 
                    this.gridSize * 0.7, 
                    this.gridSize * 0.7
                );
                break;
        }
        
        // 绘制倒计时进度条
        const remainingTime = this.specialFoodTimer / 15000; // 归一化到0-1
        const barWidth = this.gridSize * 0.8;
        const barHeight = 3;
        const barX = this.specialFood.x * this.gridSize + (this.gridSize - barWidth) / 2;
        const barY = this.specialFood.y * this.gridSize - barHeight - 5;
        
        // 背景条
        this.ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
        this.ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 进度条
        this.ctx.fillStyle = 'rgba(255, 255, 0, 0.8)';
        this.ctx.fillRect(barX, barY, barWidth * remainingTime, barHeight);
    }
    
    // 绘制暂停指示器
    drawPauseIndicator() {
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        this.ctx.fillStyle = 'white';
        this.ctx.font = '30px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        this.ctx.fillText('游戏暂停', this.canvas.width / 2, this.canvas.height / 2);
        
        this.ctx.font = '16px Arial';
        this.ctx.fillText('按空格键继续', this.canvas.width / 2, this.canvas.height / 2 + 40);
    }
    
    // 游戏主循环
    gameLoop() {
        if (!this.gameRunning || this.gamePaused) return;
        
        // 移动蛇
        this.moveSnake();
        
        // 渲染画面
        this.render();
        
        // 设置下一次循环
        this.gameLoopId = setTimeout(() => {
            requestAnimationFrame(this.gameLoop.bind(this));
        }, this.speed);
    }
}

// 当页面加载完成后，初始化游戏
window.addEventListener('DOMContentLoaded', () => {
    const game = new SnakeGame();
});